package gold.digger;

import gold.utils.InputUtil;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC930 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int numSubarraysWithSum(int[] arr, int s) {
            if (arr == null || arr.length < s) return 0;

            Map<Integer, Integer> map = new HashMap<>();
            int preSum = 0, count = 0, target = 0;

            for (int i = 0; i < arr.length; i++) {
                preSum += arr[i];
                if (preSum == s) ++count;// 前缀统计，缺少了统计arr[0]...arr[i]之和为s的情况

                target = preSum - s;
                if (map.containsKey(target)) {
                    count += map.get(target);
                }
                map.put(preSum, map.getOrDefault(preSum, 0) + 1);
            }

            return count;
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[0,0,1,0]");
        System.out.println(solution.numSubarraysWithSum(arr, 0));
    }

    public static void main(String[] args) throws Exception {
        LC930 an = new LC930();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
